// JavaScript Document
var $ = function (id) {  
    return "string" == typeof id ? document.getElementById(id) : id;  
}
function cancelclick()
{
	 window.parent.gotopage("teachoose");
}
function getorderid(id)
{
	var num = id.toString().length;
	var prefix = "";
	if(num<8)
	{
	 for(var i=0;i<8-num;i++)
	   prefix+="0";
	}
	return (prefix+id.toString());
}
function submitauthcode()
{
	//支付成功
	if(event.keyCode==13)
	{
		 var a = event.srcElement?event.srcElement:event.target;
		 if(a.id!="auth_code") return;
		 else
		 {
			 $("level4").innerHTML="已完成扫码，请等待服务器返回";
			 $("cancelclickdiv").style.display="none";
			 $("auth_code").readOnly=true;
		 }
		var code = $("auth_code").value;
		
		var json = {auth_code:code,fee:1};
	
	//	var json = {auth_code:"130584341218488904",fee:1};
	jQuery.ajax({
		type: 'POST',
		url: 'http://www.szzt.com.cn/weixinTest/native/ajax.php',
		data: json,
		success: function(obj){
			
			if(obj == 'SUCCESS'){
				sqltablename = "ORDER_INFO";
				sqltableitem = ["totalprice","totalnum","paymethod","tid","ordertime"];
				var insertvalue = new Array();
				insertvalue.push(parent._totalprice);
				insertvalue.push(parent._totalnum);
				insertvalue.push("2");

				//select id 出来
				var loadstring = "select max(id) as mid from "+sqltablename;

				sqlProvider.loadTable(loadstring,[],function(result){

					if(result.rows.length==0)
					{

						parent._orderno = getorderid("0");
					}
					else
					{

						if(result.rows.item(0).mid==null) parent._orderno = getorderid("0");
						else  parent._orderno = getorderid(parseInt(result.rows.item(0).mid)+1);
					}
					insertvalue.push( parent._orderno );
					var times = gettimes();
					insertvalue.push(times);
					sqlProvider.insertRow(sqltablename,sqltableitem,insertvalue,function(id)
					{

						var sqls = "insert into ORDER_DETAIL(orderid,goodsid,goods_num)  select "+id+",goodsid,goods_num from TORDER_DETAIL";

						sqlProvider.loadTable(sqls);

						imgAlert("../img/success.png","付款成功，谢谢您的惠顾",null,{width:600,height:300,left:200,top:61},"打印完毕之后点击确定","button");
						//addEventHandler($("cancelclickdiv"),"click",cancelclick);
						printorder();
					});
				})
			}else{
				sAlert(null,{width:300,height:150,left:320,top:160},"服务器返回错误","auto");
				window.parent.gotopage("goodscart");
			}
		} ,
		timeout: 60000, //超时时间：30秒
		error: function(XMLHttpRequest, textStatus, errorThrown){
			//TODO: 处理status， http status code，超时 408

			// 注意：如果发生了错误，错误信息（第二个参数）除了得到null之外，还可能
		
			//alert(XMLHttpRequest.readyState);
			//alert(textStatus);
			//是"timeout", "error", "notmodified" 和 "parsererror"。
			
			if(textStatus == 'timeout'){
				sAlert(null,{width:300,height:150,left:320,top:160},"网络超时，请选择其他支付方式","auto");
			}else if(textStatus == 'error'){
				 
				 sAlert(null,{width:300,height:150,left:320,top:160},"服务器返回错误","auto");
				 window.parent.gotopage("goodscart");
			}
			else
			{
				 sAlert(null,{width:300,height:150,left:320,top:160},"其他错误","auto");
			}
		}
	});

		 
	}
}

function printorder()
{
	
	var orderno = parent._orderno;
	var printstr = "";
	var tgoods_name ="";
	var tgoods_perprice = 0;
	var tgoods_num = 0;

	
	var loadstring = "select goods_name,goods_sellperprice,goods_num  from TEA_INFO,TORDER_DETAIL where TEA_INFO.id=TORDER_DETAIL.goodsid and goods_num!=0 order by TORDER_DETAIL.id asc";
	
	sqlProvider.loadTable(loadstring,[],function(result){
		
	  if(result.rows.length==0)
	  {
	     console.log("error");
	  }
	  else
	  {
		 var goodlist =  new Array();
		  for(var i=0;i<result.rows.length;i++)
		  {
			 
			   tgoods_name = result.rows.item(i).goods_name;
			   tgoods_perprice = result.rows.item(i).goods_sellperprice;
			  tgoods_num = result.rows.item(i).goods_num;
			  printstr += (i+1).toString()+"    "+tgoods_name+"      "+tgoods_num+"     "+ tgoods_perprice+"\n";
			  
		      goodlist[i] = new Object;
		      goodlist[i].goods_name = tgoods_name;
		      goodlist[i].goods_num = (i+1).toString();
		      goodlist[i].goods_price = tgoods_perprice;
		  }
		  var results="行数："+parent._totalrows+" 件数："+parent._totalnum+" 合计："+parent._totalprice+"元\n微信支付："+parent._totalprice+"元";
	var str = "        欢迎光临奶茶店\n";
	str+="单号:"+orderno+"\n";
	str+="=============================\n";
	str+="序号   商品名称     数量     单价\n";
	str+="=============================\n";
	str+=printstr;
	str+="=============================\n";
	str+=results;
	str+="\n";
	
	var type = 2;
	transferdata(orderno,goodlist,results);
	doPrintReception(type,str);
	  }});
	
	
	
	//doPrintReception(type,str);
  
    	
	//TDS.Device.PrinterService.ReceiptPrinter.sigPrintFormCompleted.connect(onPrintFromCompleted);
	//TDS.Device.PrinterService.ReceiptPrinter.printForm("payTitle",str);			
}

function init()
{
	
   addEventHandler($("cancelclickdiv"),"click",cancelclick); 
    addEventHandler($("auth_code"),"keydown",submitauthcode); 
	try{
	 this.sqlProvider = window.parent.sqlProvider;
	 sqlProvider = window.parent.sqlProvider;
	}
	catch(e){
	}
  $("totalprice").innerHTML = parent._totalprice;
   $("auth_code").focus();
   
}

   

window.onload = init;